<template>
	<view class="my-container">
		<view class="top">
			<view class="avatar">
				<img :src="userinfo.avatarUrl || defaultAvatar" alt="" />
			</view>
			<view class="information">
				<view class="name">{{ username }}</view>
			</view>
		</view>
		<view class="body">
			<view class="item" @click="editInfo">
				编辑个人信息
			</view>
			<view class="item" @click="logout">
				退出登陆
			</view>
		</view>
		<view class="editDialog" v-if="editDialogFlag">
			<Avatar :currentAvatar="userinfo.avatar" @uploadSuccess="handleUploadSuccess"
				@uploadError="handleUploadError" />
			<view class="row">
				<view class="txt">
					用户名
				</view>
				<input class="input" type="text" v-model="username">
			</view>
			<view class="row">
				<view class="btn" @click="editDialogFlag = false">关闭</view>
				<view class="btn" @click="confirmEdit">确认</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	onBeforeMount
} from 'vue';

const defaultAvatar = '/static/default-avatar.png';
const username = ref('');
const userinfo = ref(uni.getStorageSync('userInfo'));
const editDialogFlag = ref(false);

onBeforeMount(() => {
	username.value = userinfo.value.username;
});

// 处理头像上传成功
const handleUploadSuccess = async (result) => {
	try {
		// 调用云函数更新用户头像
		const res = await uniCloud.callFunction({
			name: 'updateAvatar',
			data: {
				avatarUrl: result.fileID,
				userId: userinfo.value._id
			}
		});

		if (res.result.code === 0) {
			// 更新本地存储的用户信息
			const newUserInfo = {
				...userinfo.value,
				avatarUrl: result.fileID // 使用与数据库一致的字段名
			};
			uni.setStorageSync('userInfo', newUserInfo);
			userinfo.value = newUserInfo;

			uni.showToast({
				title: '修改头像成功',
				icon: 'success'
			});
		} else {
			// 如果更新失败，需要删除刚上传的新头像
			try {
				await uniCloud.deleteFile({
					fileList: [result.fileID]
				});
			} catch (deleteErr) {
				console.error('删除失败的头像文件失败:', deleteErr);
			}
			throw new Error(res.result.msg || '更新失败');
		}
	} catch (err) {
		console.error('更新头像失败:', err);
		uni.showToast({
			title: '更新失败',
			icon: 'none'
		});
	}
};

// 处理头像上传错误
const handleUploadError = (error) => {
	console.error('上传失败:', error);
	uni.showToast({
		title: '上传失败',
		icon: 'none'
	});
};

const editInfo = () => {
	editDialogFlag.value = true;
};

const confirmEdit = () => {
	editDialogFlag.value = false;
};

const logout = () => {
	// 询问用户是否退出
	uni.showModal({
		title: '提示',
		content: '确定要退出吗？',
		success: res => {
			if (res.confirm) {
				uni.removeStorageSync('userInfo');
				uni.removeStorageSync('token');
				uni.removeStorageSync('familyName');
				uni.removeStorageSync('members');
				uni.removeStorageSync('cate');
				uni.removeStorageSync('family_Id');
				uni.reLaunch({ url: '/pages/login/login' });
			}
		}
	});
};
</script>

<style scoped lang="scss">
@import "../../uni.scss";

.my-container {
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: $base-color1;

	.top {
		width: 100%;
		flex: 1;
		display: flex;
		background-color: $base-color2;

		.avatar {
			flex: 1;
			margin-top: 30rpx;
			box-sizing: border-box;
			display: flex;
			border-radius: 50%;

			img {
				width: 150rpx;
				height: 150rpx;
				border-radius: 50%;
				border: 1px solid #ccc;
				margin-left: 40rpx;
			}
		}

		.information {
			margin-top: 30rpx;
			box-sizing: border-box;
			flex: 2;

			.name {
				width: 100%;
				font-size: 40rpx;
				font-weight: 600;
				border-radius: 10rpx;
				color: $title-color;
			}
		}
	}

	.body {
		flex: 4;
		background-color: $base-color1;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 10rpx;

		.item {
			color: $title-color;
			width: 90%;
			height: 80rpx;
			background-color: $base-color2;
			box-sizing: border-box;
			text-align: center;
			font-size: 30rpx;
			line-height: 80rpx;
			border-bottom: 1px solid #ccc;
			border-radius: 30rpx;

			&:active {
				background-color: $btn-danger-color;
			}

			&:nth-child(1) {
				margin-top: 30rpx;
			}
		}
	}
}

.editDialog {
	position: fixed;
	width: 100%;
	height: 100%;
	left: 0;
	top: 0;
	background-color: #fff;
	z-index: 999;
	display: flex;
	flex-direction: column;
	justify-content: space-around;
	align-items: center;

	.row {
		display: flex;
		justify-content: space-around;
		gap: 40rpx;

		.txt {
			height: 60rpx;
			line-height: 60rpx;
			font-size: 30rpx;
		}

		.input {
			height: 60rpx;
			border: 1px solid #ccc;
			border-radius: 20rpx;
			padding-left: 20rpx;

			&:focus {
				border: 1px solid #000;
			}
		}
	}

	.btn {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #007aff;
		color: #fff;
		border-radius: 40rpx;
		margin-bottom: 40rpx;

		&:active {
			background-color: $btn-danger-color;
		}
	}
}
</style>